package com.yegs.jltqc.serviceImpl;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.VO.BaseRole;
import com.yegs.jltqc.VO.BaseUser;
import com.yegs.jltqc.common.StoreException;
import com.yegs.jltqc.dao.BaseRoleRepository;
import com.yegs.jltqc.service.BaseRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BaseRoleServiceImpl implements BaseRoleService {

    @Autowired
    private BaseRoleRepository baseRoleRepository;

    @Override
    public void save(BaseRole baseRole) throws StoreException {
        if(baseRole.getId() == null){
            BaseRole role = baseRoleRepository.findBaseRoleByName(baseRole.getName());
            if(role != null){
                throw new StoreException("角色已存在!");
            }
            baseRoleRepository.save(baseRole);
        }else{
            BaseRole role = baseRoleRepository.getOne(baseRole.getId());
            if(role == null){
                throw new StoreException("系统错误!");
            }
            role.setName(baseRole.getName());
            role.setDescribe(baseRole.getDescribe());
            baseRoleRepository.save(role);
        }
    }

    @Override
    public List<BaseRole> list() {
        return baseRoleRepository.findAll();
    }

    @Override
    public BaseRole get(Long id) {
        return baseRoleRepository.getOne(id);
    }

    @Override
    public void del(Long id) {
        baseRoleRepository.deleteById(id);
    }

    @Override
    public Page<BaseRole> query(NamePageQuery query) {
        PageRequest request = PageRequest.of(query.getPageIndex() - 1, query.getPageSize());
        if(query.getName() == null || query.getName().trim() == ""){
            return baseRoleRepository.findAll(request);
        }
        return baseRoleRepository.findBaseRoleByName(query.getName(), request);
    }

}


